<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>外部块 - The Rust Reference</title>


        <!-- Custom HTML head -->
        
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff">

        <link rel="icon" href="../favicon.svg">
        <link rel="shortcut icon" href="../favicon.png">
        <link rel="stylesheet" href="../css/variables.css">
        <link rel="stylesheet" href="../css/general.css">
        <link rel="stylesheet" href="../css/chrome.css">
        <link rel="stylesheet" href="../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../highlight.css">
        <link rel="stylesheet" href="../tomorrow-night.css">
        <link rel="stylesheet" href="../ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        <link rel="stylesheet" href="../theme/reference.css">

    </head>
    <body class="sidebar-visible no-js">
    <div id="body-container">
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('light')
            html.classList.add(theme);
            var body = document.querySelector('body');
            body.classList.remove('no-js')
            body.classList.add('js');
        </script>

        <input type="checkbox" id="sidebar-toggle-anchor" class="hidden">

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var body = document.querySelector('body');
            var sidebar = null;
            var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            } else {
                sidebar = 'hidden';
            }
            sidebar_toggle.checked = sidebar === 'visible';
            body.classList.remove('sidebar-visible');
            body.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="../翻译说明.html">翻译说明</a></li><li class="chapter-item expanded affix "><a href="../introduction.html">介绍</a></li><li class="chapter-item expanded "><a href="../notation.html"><strong aria-hidden="true">1.</strong> 表义符</a></li><li class="chapter-item expanded "><a href="../lexical-structure.html"><strong aria-hidden="true">2.</strong> 词法结构</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../input-format.html"><strong aria-hidden="true">2.1.</strong> 输入格式</a></li><li class="chapter-item expanded "><a href="../keywords.html"><strong aria-hidden="true">2.2.</strong> 关键字</a></li><li class="chapter-item expanded "><a href="../identifiers.html"><strong aria-hidden="true">2.3.</strong> 标识符</a></li><li class="chapter-item expanded "><a href="../comments.html"><strong aria-hidden="true">2.4.</strong> 注释</a></li><li class="chapter-item expanded "><a href="../whitespace.html"><strong aria-hidden="true">2.5.</strong> 空白符</a></li><li class="chapter-item expanded "><a href="../tokens.html"><strong aria-hidden="true">2.6.</strong> token</a></li></ol></li><li class="chapter-item expanded "><a href="../macros.html"><strong aria-hidden="true">3.</strong> 宏</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../macros-by-example.html"><strong aria-hidden="true">3.1.</strong> 声明宏</a></li><li class="chapter-item expanded "><a href="../procedural-macros.html"><strong aria-hidden="true">3.2.</strong> 过程宏</a></li></ol></li><li class="chapter-item expanded "><a href="../crates-and-source-files.html"><strong aria-hidden="true">4.</strong> crate 和源文件</a></li><li class="chapter-item expanded "><a href="../conditional-compilation.html"><strong aria-hidden="true">5.</strong> 条件编译</a></li><li class="chapter-item expanded "><a href="../items.html"><strong aria-hidden="true">6.</strong> 程序项</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../items/modules.html"><strong aria-hidden="true">6.1.</strong> 模块</a></li><li class="chapter-item expanded "><a href="../items/extern-crates.html"><strong aria-hidden="true">6.2.</strong> 外部crate</a></li><li class="chapter-item expanded "><a href="../items/use-declarations.html"><strong aria-hidden="true">6.3.</strong> use声明</a></li><li class="chapter-item expanded "><a href="../items/functions.html"><strong aria-hidden="true">6.4.</strong> 函数</a></li><li class="chapter-item expanded "><a href="../items/type-aliases.html"><strong aria-hidden="true">6.5.</strong> 类型别名</a></li><li class="chapter-item expanded "><a href="../items/structs.html"><strong aria-hidden="true">6.6.</strong> 结构体</a></li><li class="chapter-item expanded "><a href="../items/enumerations.html"><strong aria-hidden="true">6.7.</strong> 枚举</a></li><li class="chapter-item expanded "><a href="../items/unions.html"><strong aria-hidden="true">6.8.</strong> 联合体</a></li><li class="chapter-item expanded "><a href="../items/constant-items.html"><strong aria-hidden="true">6.9.</strong> 常量项</a></li><li class="chapter-item expanded "><a href="../items/static-items.html"><strong aria-hidden="true">6.10.</strong> 静态项</a></li><li class="chapter-item expanded "><a href="../items/traits.html"><strong aria-hidden="true">6.11.</strong> trait</a></li><li class="chapter-item expanded "><a href="../items/implementations.html"><strong aria-hidden="true">6.12.</strong> 实现</a></li><li class="chapter-item expanded "><a href="../items/external-blocks.html" class="active"><strong aria-hidden="true">6.13.</strong> 外部块</a></li><li class="chapter-item expanded "><a href="../items/generics.html"><strong aria-hidden="true">6.14.</strong> 泛型参数</a></li><li class="chapter-item expanded "><a href="../items/associated-items.html"><strong aria-hidden="true">6.15.</strong> 关联程序项</a></li></ol></li><li class="chapter-item expanded "><a href="../attributes.html"><strong aria-hidden="true">7.</strong> 属性</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../attributes/testing.html"><strong aria-hidden="true">7.1.</strong> 测试</a></li><li class="chapter-item expanded "><a href="../attributes/derive.html"><strong aria-hidden="true">7.2.</strong> 派生</a></li><li class="chapter-item expanded "><a href="../attributes/diagnostics.html"><strong aria-hidden="true">7.3.</strong> 诊断</a></li><li class="chapter-item expanded "><a href="../attributes/codegen.html"><strong aria-hidden="true">7.4.</strong> 代码生成</a></li><li class="chapter-item expanded "><a href="../attributes/limits.html"><strong aria-hidden="true">7.5.</strong> 极限值设置</a></li><li class="chapter-item expanded "><a href="../attributes/type_system.html"><strong aria-hidden="true">7.6.</strong> 类型系统</a></li><li class="chapter-item expanded "><a href="../attributes/debugger.html"><strong aria-hidden="true">7.7.</strong> 调试器</a></li></ol></li><li class="chapter-item expanded "><a href="../statements-and-expressions.html"><strong aria-hidden="true">8.</strong> 语句和表达式</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../statements.html"><strong aria-hidden="true">8.1.</strong> 语句</a></li><li class="chapter-item expanded "><a href="../expressions.html"><strong aria-hidden="true">8.2.</strong> 表达式</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../expressions/literal-expr.html"><strong aria-hidden="true">8.2.1.</strong> 字面量表达式</a></li><li class="chapter-item expanded "><a href="../expressions/path-expr.html"><strong aria-hidden="true">8.2.2.</strong> 路径表达式</a></li><li class="chapter-item expanded "><a href="../expressions/block-expr.html"><strong aria-hidden="true">8.2.3.</strong> 块表达式</a></li><li class="chapter-item expanded "><a href="../expressions/operator-expr.html"><strong aria-hidden="true">8.2.4.</strong> 运算符表达式</a></li><li class="chapter-item expanded "><a href="../expressions/grouped-expr.html"><strong aria-hidden="true">8.2.5.</strong> 分组表达式</a></li><li class="chapter-item expanded "><a href="../expressions/array-expr.html"><strong aria-hidden="true">8.2.6.</strong> 数组和索引表达式</a></li><li class="chapter-item expanded "><a href="../expressions/tuple-expr.html"><strong aria-hidden="true">8.2.7.</strong> 元组和索引表达式</a></li><li class="chapter-item expanded "><a href="../expressions/struct-expr.html"><strong aria-hidden="true">8.2.8.</strong> 结构体表达式</a></li><li class="chapter-item expanded "><a href="../expressions/call-expr.html"><strong aria-hidden="true">8.2.9.</strong> 调用表达式</a></li><li class="chapter-item expanded "><a href="../expressions/method-call-expr.html"><strong aria-hidden="true">8.2.10.</strong> 方法调用表达式</a></li><li class="chapter-item expanded "><a href="../expressions/field-expr.html"><strong aria-hidden="true">8.2.11.</strong> 字段访问表达式</a></li><li class="chapter-item expanded "><a href="../expressions/closure-expr.html"><strong aria-hidden="true">8.2.12.</strong> 闭包表达式</a></li><li class="chapter-item expanded "><a href="../expressions/loop-expr.html"><strong aria-hidden="true">8.2.13.</strong> 循环表达式</a></li><li class="chapter-item expanded "><a href="../expressions/range-expr.html"><strong aria-hidden="true">8.2.14.</strong> 区间表达式</a></li><li class="chapter-item expanded "><a href="../expressions/if-expr.html"><strong aria-hidden="true">8.2.15.</strong> if 和 if let 表达式</a></li><li class="chapter-item expanded "><a href="../expressions/match-expr.html"><strong aria-hidden="true">8.2.16.</strong> 匹配表达式</a></li><li class="chapter-item expanded "><a href="../expressions/return-expr.html"><strong aria-hidden="true">8.2.17.</strong> 返回表达式</a></li><li class="chapter-item expanded "><a href="../expressions/await-expr.html"><strong aria-hidden="true">8.2.18.</strong> 等待(await)表达式</a></li><li class="chapter-item expanded "><a href="../expressions/underscore-expr.html"><strong aria-hidden="true">8.2.19.</strong> 下划线表达式</a></li></ol></li></ol></li><li class="chapter-item expanded "><a href="../patterns.html"><strong aria-hidden="true">9.</strong> 模式</a></li><li class="chapter-item expanded "><a href="../type-system.html"><strong aria-hidden="true">10.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../types.html"><strong aria-hidden="true">10.1.</strong> 类型</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../types/boolean.html"><strong aria-hidden="true">10.1.1.</strong> 布尔型</a></li><li class="chapter-item expanded "><a href="../types/numeric.html"><strong aria-hidden="true">10.1.2.</strong> 数字型</a></li><li class="chapter-item expanded "><a href="../types/textual.html"><strong aria-hidden="true">10.1.3.</strong> 字符型</a></li><li class="chapter-item expanded "><a href="../types/never.html"><strong aria-hidden="true">10.1.4.</strong> never类型</a></li><li class="chapter-item expanded "><a href="../types/tuple.html"><strong aria-hidden="true">10.1.5.</strong> 元组</a></li><li class="chapter-item expanded "><a href="../types/array.html"><strong aria-hidden="true">10.1.6.</strong> 数组</a></li><li class="chapter-item expanded "><a href="../types/slice.html"><strong aria-hidden="true">10.1.7.</strong> 切片</a></li><li class="chapter-item expanded "><a href="../types/struct.html"><strong aria-hidden="true">10.1.8.</strong> 结构体</a></li><li class="chapter-item expanded "><a href="../types/enum.html"><strong aria-hidden="true">10.1.9.</strong> 枚举</a></li><li class="chapter-item expanded "><a href="../types/union.html"><strong aria-hidden="true">10.1.10.</strong> 联合体</a></li><li class="chapter-item expanded "><a href="../types/function-item.html"><strong aria-hidden="true">10.1.11.</strong> 函数项类型</a></li><li class="chapter-item expanded "><a href="../types/closure.html"><strong aria-hidden="true">10.1.12.</strong> 闭包</a></li><li class="chapter-item expanded "><a href="../types/pointer.html"><strong aria-hidden="true">10.1.13.</strong> 指针型</a></li><li class="chapter-item expanded "><a href="../types/function-pointer.html"><strong aria-hidden="true">10.1.14.</strong> 函数指针</a></li><li class="chapter-item expanded "><a href="../types/trait-object.html"><strong aria-hidden="true">10.1.15.</strong> trait对象</a></li><li class="chapter-item expanded "><a href="../types/impl-trait.html"><strong aria-hidden="true">10.1.16.</strong> 实现trait</a></li><li class="chapter-item expanded "><a href="../types/parameters.html"><strong aria-hidden="true">10.1.17.</strong> 类型参数</a></li><li class="chapter-item expanded "><a href="../types/inferred.html"><strong aria-hidden="true">10.1.18.</strong> 可推断类型</a></li></ol></li><li class="chapter-item expanded "><a href="../dynamically-sized-types.html"><strong aria-hidden="true">10.2.</strong> 动态内存宽度类型(DST)</a></li><li class="chapter-item expanded "><a href="../type-layout.html"><strong aria-hidden="true">10.3.</strong> 类型布局 </a></li><li class="chapter-item expanded "><a href="../interior-mutability.html"><strong aria-hidden="true">10.4.</strong> 内部可变性</a></li><li class="chapter-item expanded "><a href="../subtyping.html"><strong aria-hidden="true">10.5.</strong> 子类型和型变</a></li><li class="chapter-item expanded "><a href="../trait-bounds.html"><strong aria-hidden="true">10.6.</strong> trait约束及其生存期约束</a></li><li class="chapter-item expanded "><a href="../type-coercions.html"><strong aria-hidden="true">10.7.</strong> 类型自动强转</a></li><li class="chapter-item expanded "><a href="../destructors.html"><strong aria-hidden="true">10.8.</strong> 析构函数</a></li><li class="chapter-item expanded "><a href="../lifetime-elision.html"><strong aria-hidden="true">10.9.</strong> 生存期省略</a></li></ol></li><li class="chapter-item expanded "><a href="../special-types-and-traits.html"><strong aria-hidden="true">11.</strong> 特殊类型和 trait</a></li><li class="chapter-item expanded "><a href="../names.html"><strong aria-hidden="true">12.</strong> 名称</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../names/namespaces.html"><strong aria-hidden="true">12.1.</strong> 命名空间</a></li><li class="chapter-item expanded "><a href="../names/scopes.html"><strong aria-hidden="true">12.2.</strong> 作用域</a></li><li class="chapter-item expanded "><a href="../names/preludes.html"><strong aria-hidden="true">12.3.</strong> 预导入包</a></li><li class="chapter-item expanded "><a href="../paths.html"><strong aria-hidden="true">12.4.</strong> 路径</a></li><li class="chapter-item expanded "><a href="../names/name-resolution.html"><strong aria-hidden="true">12.5.</strong> 名称解析</a></li><li class="chapter-item expanded "><a href="../visibility-and-privacy.html"><strong aria-hidden="true">12.6.</strong> 可见性与隐私权</a></li></ol></li><li class="chapter-item expanded "><a href="../memory-model.html"><strong aria-hidden="true">13.</strong> 内存模型</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../memory-allocation-and-lifetime.html"><strong aria-hidden="true">13.1.</strong> 内存分配和生存期</a></li><li class="chapter-item expanded "><a href="../variables.html"><strong aria-hidden="true">13.2.</strong> 变量</a></li></ol></li><li class="chapter-item expanded "><a href="../linkage.html"><strong aria-hidden="true">14.</strong> 链接</a></li><li class="chapter-item expanded "><a href="../inline-assembly.html"><strong aria-hidden="true">15.</strong> 内联汇编</a></li><li class="chapter-item expanded "><a href="../unsafety.html"><strong aria-hidden="true">16.</strong> 非安全性</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../unsafe-keyword.html"><strong aria-hidden="true">16.1.</strong> T关键字unsafe</a></li><li class="chapter-item expanded "><a href="../behavior-considered-undefined.html"><strong aria-hidden="true">16.2.</strong> 未定义行为</a></li><li class="chapter-item expanded "><a href="../behavior-not-considered-unsafe.html"><strong aria-hidden="true">16.3.</strong> 不被认为是非安全的行为</a></li></ol></li><li class="chapter-item expanded "><a href="../const_eval.html"><strong aria-hidden="true">17.</strong> 常量求值</a></li><li class="chapter-item expanded "><a href="../abi.html"><strong aria-hidden="true">18.</strong> ABI</a></li><li class="chapter-item expanded "><a href="../runtime.html"><strong aria-hidden="true">19.</strong> Rust运行时</a></li><li class="chapter-item expanded "><a href="../appendices.html"><strong aria-hidden="true">20.</strong> 附录</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../macro-ambiguity.html"><strong aria-hidden="true">20.1.</strong> 宏规范</a></li><li class="chapter-item expanded "><a href="../influences.html"><strong aria-hidden="true">20.2.</strong> 影响来源</a></li><li class="chapter-item expanded "><a href="../glossary.html"><strong aria-hidden="true">20.3.</strong> 术语表</a></li><li class="chapter-item expanded "><a href="../本书术语翻译对照表.html"><strong aria-hidden="true">20.4.</strong> 本书术语翻译对照表</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle">
                <div class="sidebar-resize-indicator"></div>
            </div>
        </nav>

        <!-- Track and set sidebar scroll position -->
        <script>
            var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
            sidebarScrollbox.addEventListener('click', function(e) {
                if (e.target.tagName === 'A') {
                    sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
                }
            }, { passive: true });
            var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
            sessionStorage.removeItem('sidebar-scroll');
            if (sidebarScrollTop) {
                // preserve sidebar scroll position when navigating via links within sidebar
                sidebarScrollbox.scrollTop = sidebarScrollTop;
            } else {
                // scroll sidebar to current active section when navigating via "next/previous chapter" buttons
                var activeSection = document.querySelector('#sidebar .active');
                if (activeSection) {
                    activeSection.scrollIntoView({ block: 'center' });
                }
            }
        </script>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky">
                    <div class="left-buttons">
                        <label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </label>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">The Rust Reference</h1>

                    <div class="right-buttons">
                        <a href="../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        <a href="https://github.com/rust-lang/reference/" title="Git repository" aria-label="Git repository">
                            <i id="git-repository-button" class="fa fa-github"></i>
                        </a>
                        <a href="https://github.com/rust-lang/reference/edit/master/src/items/external-blocks.md" title="Suggest an edit" aria-label="Suggest an edit">
                            <i id="git-edit-button" class="fa fa-edit"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="external-blocks"><a class="header" href="#external-blocks">External blocks</a></h1>
<h1 id="外部块"><a class="header" href="#外部块">外部块</a></h1>
<blockquote>
<p><a href="https://github.com/rust-lang/reference/blob/master/src/items/external-blocks.md">external-blocks.md</a><br />
commit: 875b905a389455c5329ae088600c0b5f7222104d <br />
本章译文最后维护日期：2024-08-18</p>
</blockquote>
<blockquote>
<p><strong><sup>句法</sup></strong><br />
<em>ExternBlock</em> :<br />
   <code>unsafe</code><sup>?</sup> <code>extern</code> <a href="functions.html"><em>Abi</em></a><sup>?</sup> <code>{</code><br />
      <a href="../attributes.html"><em>InnerAttribute</em></a><sup>*</sup><br />
      <em>ExternalItem</em><sup>*</sup><br />
   <code>}</code></p>
<p><em>ExternalItem</em> :<br />
   <a href="../attributes.html"><em>OuterAttribute</em></a><sup>*</sup> (<br />
         <a href="../macros.html#macro-invocation"><em>MacroInvocationSemi</em></a><br />
      | ( <a href="../visibility-and-privacy.html"><em>Visibility</em></a><sup>?</sup> ( <a href="static-items.html"><em>StaticItem</em></a> | <a href="functions.html"><em>Function</em></a> ) )<br />
   )</p>
</blockquote>
<p>外部块提供未在当前 crate 中<em>定义</em>的程序项的<em>声明</em>，外部块是 Rust 外部函数接口的基础。这其实是某种意义上的不受安全检查的导入入口。</p>
<p>外部块里允许存在两种形式的程序项<em>声明</em>：<a href="functions.html">函数</a>和<a href="static-items.html">静态项</a>。只有在非安全(<code>unsafe</code>)上下文中才能调用在外部块中声明的函数或访问在外部块中声明的静态项。</p>
<p>外部块在其所在模块或块的<a href="../names/namespaces.html">值命名空间</a>中定义其函数和静态项。</p>
<h2 id="functions"><a class="header" href="#functions">Functions</a></h2>
<h2 id="函数"><a class="header" href="#函数">函数</a></h2>
<p>外部块中的函数与其他 Rust函数的声明方式相同，但这里的函数不能有函数体，取而代之的是直接以分号结尾。参数中不允许使用模式，只能直接使用<a href="../identifiers.html">标识符</a>或<code>_</code>。允许使用 <code>safe</code> 和 <code>unsafe</code> 这两个函数限定符，但不允许使用其他函数限定符（例如 <code>const</code>、<code>async</code>、<code>extern</code>）。</p>
<p>外部块中的函数可以被 Rust 代码调用，就跟调用在 Rust 中定义的函数一样。Rust 编译器会自动在 Rust ABI 和外部 ABI 之间进行转换。</p>
<p>在外部块中声明的函数隐式为非安全(<code>unsafe</code>)的，但 <code>safe</code> 限定的函数除外。</p>
<p>当强转为函数指针时，外部块中声明的函数的类型为 <code>extern "abi" for&lt;'l1, ..., 'lm&gt; fn(A1, ..., An) -&gt; R</code>，其中 <code>'l1</code>，…<code>'lm</code> 是其生存期参数，<code>A1</code>，…，<code>An</code> 是该函数声明的参数的类型，<code>R</code> 是该声明的返回类型。</p>
<h2 id="statics"><a class="header" href="#statics">Statics</a></h2>
<h2 id="静态项"><a class="header" href="#静态项">静态项</a></h2>
<p><a href="static-items.html">静态项</a>在外部块内部与在外部块之外的声明方式相同，只是在外部块内部声明的静态项没有对应的初始化表达式。
除非在外部块中声明的静态项被限定为 <code>safe</code>，否则访问该项是 <code>unsafe</code>，无论它是否可变，因为没有任何东西可以保证静态项的内存位模式对于它所声明的类型有效，因为初始化这些静态项的可能是其他的任意外部代码（例如 C）。</p>
<p>就像外部块之外的<a href="static-items.html">静态项</a>，外部静态项可以是不可变的，也可以是可变的。
在执行任何 Rust 代码之前，不可变外部静态项<em>必须</em>被初始化。也就是说，对于外部静态项，仅在 Rust 代码读取它之前对它进行初始化是不够的。
一旦 Rust 代码运行，改变一个不可变的静态项（从Rust内部或外部）就是UB，除非变更发生在 <code>UnsafeCell</code> 内的字节上。</p>
<h2 id="abi"><a class="header" href="#abi">ABI</a></h2>
<p>不指定 ABI 字符串的默认情况下，外部块会假定使用指定平台上的标准 C ABI 约定来调用当前的库。其他的 ABI 约定可以使用字符串 <code>abi</code> 来指定，具体如下所示：</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 到 Windows API 的接口。（译者注：指定使用 stdcall调用约定去调用 Windows API）
unsafe extern "stdcall" { }
<span class="boring">}</span></code></pre></pre>
<p>有三个 ABI 字符串是跨平台的，并且保证所有编译器都支持它们：</p>
<ul>
<li><code>unsafe extern "Rust"</code> – 在任何 Rust 语言中编写的普通函数 <code>fn foo()</code> 默认使用的 ABI。</li>
<li><code>unsafe extern "C"</code> – 这等价于 <code>extern fn foo()</code>；无论您的 C编译器支持什么默认 ABI。</li>
<li><code>unsafe extern "system"</code> – 在 Win32 平台之外，中通常等价于 <code>extern "C"</code>。在 Win32 平台上，应该使用<code>"stdcall"</code>，或者其他应该使用的 ABI 字符串来链接它们自身的 Windows API。</li>
</ul>
<p>还有一些特定于平台的 ABI 字符串：</p>
<ul>
<li><code>unsafe extern "cdecl"</code> – 通过 FFI 调用 x86_32 C 资源所使用的默认调用约定。</li>
<li><code>unsafe extern "stdcall"</code> – 通过 FFI 调用 x86_32架构下的 Win32 API 所使用的默认调用约定</li>
<li><code>unsafe extern "win64"</code> – 通过 FFI 调用 x86_64 Windows 平台下的 C 资源所使用的默认调用约定。</li>
<li><code>unsafe extern "sysv64"</code> – 通过 FFI 调用 非Windows x86_64 平台下的 C 资源所使用的默认调用约定。</li>
<li><code>unsafe extern "aapcs"</code> –通过 FFI 调用 ARM 接口所使用的默认调用约定</li>
<li><code>unsafe extern "fastcall"</code> – <code>fastcall</code> ABI——对应于 MSVC 的<code>__fastcall</code> 和 GCC 以及 clang 的 <code>__attribute__((fastcall))</code>。</li>
<li><code>unsafe extern "vectorcall"</code> – <code>vectorcall</code> ABI ——对应于 MSVC 的 <code>__vectorcall</code> 和 clang 的 <code>__attribute__((vectorcall))</code>。</li>
<li><code>unsafe extern "thiscall"</code> – MSVC 下调用 C++ 成员函数的默认约定 – 对应与 MSVC 下的<code>__thiscall</code>，以及 GCC 和 clang 的<code>__attribute__((thiscall))</code> 调用约定</li>
<li><code>unsafe extern "efiapi"</code> – 调用 <a href="https://uefi.org/specifications">UEFI</a> 函数所使用的 ABI。</li>
</ul>
<h2 id="variadic-functions"><a class="header" href="#variadic-functions">Variadic functions</a></h2>
<h2 id="可变参数函数"><a class="header" href="#可变参数函数">可变参数函数</a></h2>
<p>可以在外部块内的函数的参数列表中的一个或多个具名参数后通过引入 <code>...</code> 来让该函数成为可变参数函数。可变参数可以以可选的方式通过标识符来指定：</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>unsafe extern "C" {
    safe fn foo(...);
    unsafe fn bar(x: i32, ...);
    unsafe fn with_name(format: *const u8, args: ...);
}
<span class="boring">}</span></code></pre></pre>
<h2 id="attributes-on-extern-blocks"><a class="header" href="#attributes-on-extern-blocks">Attributes on extern blocks</a></h2>
<h2 id="外部块上的属性"><a class="header" href="#外部块上的属性">外部块上的属性</a></h2>
<p>下面列出的<a href="../attributes.html">属性</a>可以控制外部块的行为。</p>
<h3 id="the-link-attribute"><a class="header" href="#the-link-attribute">The <code>link</code> attribute</a></h3>
<h3 id="link属性"><a class="header" href="#link属性"><code>link</code>属性</a></h3>
<p><em><code>link</code>属性</em>为外部(<code>extern</code>)块中的程序项指定编译器应该链接的本地库的名称。它使用 <a href="../attributes.html#meta-item-attribute-syntax"><em>MetaListNameValueStr</em></a>元项属性句法指定其输入参数。<code>name</code>键指定要链接的本地库的名称。<code>kind</code>键是一个可选值，它指定具有以下可选值的库类型：</p>
<ul>
<li><code>dylib</code> — 表示要链接的库类型是动态库。如果没有指定 <code>kind</code>，这是默认值。</li>
<li><code>static</code> — 表示要链接的库类型是静态库。</li>
<li><code>framework</code> — 表示要链接的库类型是 macOS 框架。这只对 macOS 目标平台有效。</li>
<li><code>raw-dylib</code> — 表示要链接的库类型是动态库，但具体要链接到哪个动态库，链接器会使用本次编译出的库作为导入库来定位识别链接，（相关详细信息，请参阅下面的<a href="#dylib-versus-raw-dylib"><code>dylib</code> vs <code>rawdylib</code></a>）。此属性仅对 Windows目标平台有效。</li>
</ul>
<p>如果指定了 <code>kind</code>键，则必须有 <code>name</code>键。</p>
<p>可选的 <code>modifiers</code>参数提供了一种为库指定链接修饰符的方法。
修饰符被指定为以逗号分隔的字符串，每个修饰符的前缀都是 <code>+</code> 或 <code>-</code>，分别表示修饰符处于启用或禁用状态。
当前不支持在单个 <code>link</code>属性中指定多个 <code>modifiers</code>参数，或在同一个 <code>modifiers</code>参数中指定多个相同的修饰符。</p>
<p>例如: <code>#[link(name = "mylib", kind = "static", modifiers = "+whole-archive")]</code>。</p>
<p>当从主机环境导入 symbols 时，<code>wasm_import_module</code>键可用于为外部(<code>extern</code>)块中的程序项指定 <a href="https://webassembly.github.io/spec/core/syntax/modules.html">WebAssembly模块</a>名称。如果未指定 <code>wasm_import_module</code>，则默认模块名为 <code>env</code>。</p>
<!-- ignore: requires extern linking -->
<pre><code class="language-rust ignore">#[link(name = "crypto")]
unsafe extern {
    // …
}

#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern {
    // …
}

#[link(wasm_import_module = "foo")]
unsafe extern {
    // …
}</code></pre>
<p>在空外部块上添加 <code>link</code>属性是有效的。可以用这种方式来满足代码中其他地方的外部块的链接需求（包括上游 crate），而不必向每个外部块都添加此属性。</p>
<h4 id="linking-modifiers-bundle"><a class="header" href="#linking-modifiers-bundle">Linking modifiers: <code>bundle</code></a></h4>
<h4 id="链接修饰符-bundle"><a class="header" href="#链接修饰符-bundle">链接修饰符: <code>bundle</code></a></h4>
<p>这个修饰符只在静态链接模式下适用。
在其他链接模式下会导致编译错误。</p>
<p>在构建 rlib 或 staticlib 时，<code>+bundle</code> 意味着本地静态库将被打包到 rlib 或者 staticlib类型的归档文件中，之后最终的二进制文件在在链接时，将从此处来检索。</p>
<p>当构建 rlib时，<code>-bundle</code> 意味着本机静态库会被“按名称”注册为该 rlib 的依赖项，并且其中的对象文件仅在最终的二进制文件的链接过程中才被包含进来，其中最终的链接过程会执行按该名称的文件搜索来定位那些对象文件。<br />
当构建 staticlib时，<code>-bundle</code>意味着本机静态库根本不会被包括在归档文件中，一些层次更高或则说是排序更靠后的构建系统会在之后的链接最终二进制文件的过程中才来添加它。</p>
<p>在构建其他目标（如可执行文件或动态库）时，此修饰符无效。</p>
<p>此修饰符的默认形式是 <code>+bundle</code>。</p>
<p>有关此修饰符的更多实现细节，请参见<a href="https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-bundle">rustc文档中的 <code>bundle</code></a>。</p>
<h4 id="linking-modifiers-whole-archive"><a class="header" href="#linking-modifiers-whole-archive">Linking modifiers: <code>whole-archive</code></a></h4>
<h4 id="链接修饰符-whole-archive"><a class="header" href="#链接修饰符-whole-archive">链接修饰符: <code>whole-archive</code></a></h4>
<p>此修饰符仅兼容静态(<code>static</code>)链接类型。
使用任何其他链接类型都会引起编译器报错。</p>
<p><code>+whole-archive</code> 意味着静态库会被链接为一个完整的 archive 文件，而不丢弃任何对象文件。</p>
<p>此修饰符的默认配置是 <code>-whole-archive</code>。</p>
<p>有关此修饰符的更多实现细节，请参见<a href="https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-whole-archive">rustc文档中的 <code>whole-archive</code></a>。</p>
<h3 id="linking-modifiers-verbatim"><a class="header" href="#linking-modifiers-verbatim">Linking modifiers: <code>verbatim</code></a></h3>
<h3 id="链接修饰符-verbatim"><a class="header" href="#链接修饰符-verbatim">链接修饰符: <code>verbatim</code></a></h3>
<p>此修饰符兼容任何链接类型。</p>
<p><code>+verbatim</code> 意味着 rustc 本身不会在库名称中添加任何目标平台指定的库前缀或后缀（如 <code>lib</code> 或 <code>.a</code>），并且会尽力向链接器请求相同的内容。</p>
<p><code>-verbatim</code> 意味着 rustc 在将库名称传递给链接器之前，将在库名称中添加特定于目标平台的前缀和后缀，或者不会阻止链接器隐式添加它。</p>
<p>此修饰符的默认值为 <code>-verbatim</code>。</p>
<p>关于这个修饰符的更多实现细节可以在 rustc 的<a href="https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-verbatim"><code>verbatim</code>文档</a> 中找到。</p>
<h4 id="dylib-versus-raw-dylib"><a class="header" href="#dylib-versus-raw-dylib"><code>dylib</code> versus <code>raw-dylib</code></a></h4>
<h4 id="dylib-vs-raw-dylib"><a class="header" href="#dylib-vs-raw-dylib"><code>dylib</code> vs <code>raw-dylib</code></a></h4>
<p>在 Windows 上，链接动态库需要先向链接器提供一个导入库：这是一个特殊的静态库，它声明了此动态库导出的所有符号，这样链接器就知道它们必须在运行时动态加载。</p>
<p>指定 <code>kind = "dylib"</code> 将指示 Rust编译器根据 <code>name</code>键链接导入库。然后，链接器将使用其正常的库解析逻辑来查找导入库。或者，使用 <code>kind = "raw-dylib"</code> 来指示编译器在编译期间生成一个导入库，并将其提供给链接器。</p>
<p><code>raw dylib</code> 仅在 Windows 上受支持。在针对其他平台时使用它将导致编译器错误。</p>
<h4 id="the-import_name_type-key"><a class="header" href="#the-import_name_type-key">The <code>import_name_type</code> key</a></h4>
<h4 id="import_name_type键"><a class="header" href="#import_name_type键"><code>import_name_type</code>键</a></h4>
<p>在 x86 Windows上，函数的名称是“被修饰过的”（比如被添加了特定的前缀和/或后缀），以指示其支持的调用约定。例如，名为 <code>fn1</code> 且没有参数的 <code>stdcall</code>调用约定函数将被修饰为<code>_fn1@0</code>。然而，<a href="https://learn.microsoft.com/windows/win32/debug/pe-format#import-name-type">PE格式</a>也允许名称没有前缀或不加修饰。此外，MSVC和GNU工具链对相同的调用约定使用不同的装饰，这意味着，默认情况下，一些 Win32函数不能通过 GNU工具链使用 <code>raw-dylib</code>链接类型进行调用。</p>
<p>为了照顾到这些差异，在使用 <code>raw-dylib</code>链接类型时，你可以通过指定 <code>import_name_type</code>键使用下面的（某一）值来更改这些函数在生成的库文件中的命名方式：</p>
<ul>
<li><code>decorated</code>：函数名称将使用 MSVC工具链格式进行完全修饰。</li>
<li><code>noprefix</code>：函数名称将使用 MSVC工具链格式进行修饰，但跳过前导的 <code>?</code>、<code>@</code> 或者可选地 <code>_</code>。</li>
<li><code>undecorated</code>：函数名称将不会被修饰。</li>
</ul>
<p>如果未指定 <code>import_name_type</code>键，则函数名称将使用目标工具链的格式进行完全修饰。</p>
<p>变量从不会被修饰，因此 <code>import_name_type</code>键对它们在生成的库文件的命名方式没有影响。</p>
<p><code>import_name_type</code>键仅在x86 Windows上受支持。在针对其他平台时使用它将导致编译器错误。</p>
<h3 id="the-link_name-attribute"><a class="header" href="#the-link_name-attribute">The <code>link_name</code> attribute</a></h3>
<h3 id="link_name属性"><a class="header" href="#link_name属性"><code>link_name</code>属性</a></h3>
<p>可以在外部(<code>extern</code>)块内的程序项声明上指定 <em><code>link_name</code>属性</em>，可以用它来指示要为给定函数或静态项导入的具体 symbol。它使用 <a href="../attributes.html#meta-item-attribute-syntax"><em>MetaNameValueStr</em></a>元项属性句法指定 symbol 的名称。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>unsafe extern {
    #[link_name = "actual_symbol_name"]
    safe fn name_in_rust();
}
<span class="boring">}</span></code></pre></pre>
<p>此属性和 <code>link_ordinal</code>属性同时使用会导致编译器报错。</p>
<h3 id="the-link_ordinal-attribute"><a class="header" href="#the-link_ordinal-attribute">The <code>link_ordinal</code> attribute</a></h3>
<h3 id="link_ordinal属性"><a class="header" href="#link_ordinal属性"><code>link_ordinal</code>属性</a></h3>
<p><em><code>link_ordinal</code>属性</em>可以应用于外部(<code>extern</code>)块内的各种声明上，用以给当前编译生成的链接导入库在链接时要使用的数字序号。Windows 上的动态库导出的每个符号都有的唯一编号，当加载库时可以使用相应序号查找对应的符号，而不必按名称查找。</p>
<div class="warning">
<p>警告：<code>link_ordinal</code> 只能在此符号的序号已稳定了的情况下使用：如果在包含某符号的二进制文件构建时，此符号对应的序号未明确设置，则此构建将自动为其分配一个序号，并且在后续的库构建时此序号可能会在二进制文件生成之间还会发生变化。</p>
</div>
<!-- ignore: Only works on x86 Windows -->
<pre><code class="language-rust ignore">#[link(name = "exporter", kind = "raw-dylib")]
unsafe extern "stdcall" {
    #[link_ordinal(15)]
    safe fn imported_function_stdcall(i: i32);
}</code></pre>
<p>此属性仅用于 <code>raw-dylib</code>链接类型。
使用任何其他类型都会导致编译器报错。</p>
<p>此属性和 <code>link_name</code>属性同时使用会导致编译器报错。</p>
<h3 id="attributes-on-function-parameters"><a class="header" href="#attributes-on-function-parameters">Attributes on function parameters</a></h3>
<h3 id="函数参数上的属性"><a class="header" href="#函数参数上的属性">函数参数上的属性</a></h3>
<p>外部函数参数上的属性遵循与<a href="functions.html#attributes-on-function-parameters">常规函数参数</a>相同的规则和限制。</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../items/implementations.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next prefetch" href="../items/generics.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../items/implementations.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next prefetch" href="../items/generics.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script>
            window.playground_copyable = true;
        </script>


        <script src="../elasticlunr.min.js"></script>
        <script src="../mark.min.js"></script>
        <script src="../searcher.js"></script>

        <script src="../clipboard.min.js"></script>
        <script src="../highlight.js"></script>
        <script src="../book.js"></script>

        <!-- Custom JS scripts -->


    </div>
    </body>
</html>
